package cn.javabb.admin.controller.sys;

import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.model.Tree;
import cn.javabb.common.utils.BUtil;
import cn.javabb.common.utils.JSONUtils;
import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.entity.sys.RoleDO;
import cn.javabb.core.service.biz.CatalogService;
import cn.javabb.core.service.sys.MenuService;
import cn.javabb.core.service.sys.RolePermissionService;
import cn.javabb.core.service.sys.RoleService;
import cn.javabb.log.action.DeleteAction;
import cn.javabb.log.action.SaveAction;
import cn.javabb.log.annotation.EntityParam;
import cn.javabb.log.annotation.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/role")
public class RoleAdminController extends BaseController {
    
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    CatalogService catalogService;
    @Autowired
    RolePermissionService rolePermissionService;
    /**
     * 角色列表页面 
     * @author QINB
     * @param model
     * @return
     */
    @RequiresPermissions("role:view")
    @GetMapping("/list")
    public String toListPage(Model model) {
        return "admin/system/role";
    }
    /**
     * 角色授权页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/save")
    public String toSavePage(Model model) {
       /* List<Role> roles = roleService.queryAll();
        response.addAttribute("roles", roles);*/
        return "admin/system/roleSave";
    }
    /**
     * 角色授权页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/auth")
    public String toAuthPage(String roleId, Model model) {
        model.addAttribute("roleId", roleId);
       /* List<Role> roles = roleService.queryAll();
        response.addAttribute("roles", roles);*/
        return "admin/system/roleAuth";
    }
    /**
     * 查询角色列表
     */
    @RequiresPermissions("role:view")
    @ResponseBody
    @GetMapping("/")
    public Object list(String roleName) {
        String page = getPage();
        String size = getSize();
        RoleDO r = new RoleDO();
        if(StringUtils.isNotBlank(roleName)){
            r.setRoleName(roleName);
        }
        Page rolePage = roleService.queryPageByWhere(page, size, r);
        return ResponseModel.table(rolePage);
    }
    /**
     * 保存
     * @author QINB
     * @param role
     * @return
     */
    @RequiresPermissions("role:save")
    @ResponseBody
    @PostMapping("/")
    @Log(name="角色保存",action = SaveAction.class)
    public Object saveOrUpdate(@EntityParam RoleDO role){
        int num;
        if(BUtil.isNull(role.getId())){
            //insert
            role.setState(0);
            num = roleService.insertSelective(role);
        }else{
            //update
            num = roleService.updateSelective(role);
        }
        if(num>0){
            return ResponseModel.Success("保存成功");
        }
        
        return ResponseModel.Failure("保存失败");
    }
    /*角色删除*/
    @RequiresPermissions("role:del")
    @ResponseBody
    @DeleteMapping("/{ids}")
    @Log(name = "角色删除",action = DeleteAction.class)
    public Object delete(@PathVariable String ids){
        if(StringUtils.isBlank(ids)){
            return ResponseModel.Failure("参数错误");
        }
        if (roleService.isAdminRole(ids)) {
            return ResponseModel.Failure("不能删除超级管理员角色");
        }
        if (roleService.delete(ids)) {
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }
    @ResponseBody
    @GetMapping("/permissionTree")
    public Object authTree(Integer roleId){
        if(null == roleId){
            return ResponseModel.Failure("参数错误");
        }
        // 菜单权限树
        List<Tree> menuPermissionTree = menuService.checkTreeByRoleId(roleId);
        // 板块权限树
        List<Tree> catalogPermissionTree = catalogService.checkTreeByRoleId(roleId);
        Map<String, Object> map = new HashMap<>();
        map.put("menuPermissionTree", menuPermissionTree);
        map.put("catalogPermissionTree", catalogPermissionTree);
        return ResponseModel.Success(map);
    }

    /**
     * 更新角色权限
     * @param roleId
     * @param permissions
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/updateRolePermission")
    public Object updateRolePermission(Integer roleId,String permissions){
        JSONArray jsonArray = JSONObject.parseArray(permissions);
        boolean res = false;
        for (Object obj : jsonArray) {
            res = rolePermissionService.saveRolePermissions(
                    roleId,
                    JSONObject.parseObject(obj.toString()).getIntValue("type"),
                    ListUtils.listToString(JSONUtils.parseArray(JSONObject.parseObject(obj.toString()).getString("permissionIds"),Integer.class),",")
            );
            if (!res) {
                return ResponseModel.Failure("保存失败");
            }
        }
        /*for (Map.Entry<String, Object> entry : jsonArray.entrySet()) {
           // rolePermissionService.saveRolePermissions(roleId,JSONUtils.getIntValue(entry.getKey(),"type"),)
        }*/
       // boolean r1 = rolePermissionService.saveRolePermissions(roleId,JSONUtils.getIntValue("type"),)
       /* if(roleService.saveRolePermission(roleId,1, JSONUtils.parseArray(permissions, Integer.class))){
            return ResponseModel.Success("保存成功");
        }*/

        return ResponseModel.Success("保存成功");
    }
    
}
